package com.tianji.promotion.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.course.CategoryClient;
import com.tianji.api.dto.course.CategoryBasicDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.BeanUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.promotion.domain.dto.CouponFormDTO;
import com.tianji.promotion.domain.dto.CouponIssueFormDTO;
import com.tianji.promotion.domain.po.Coupon;
import com.tianji.promotion.domain.po.CouponScope;
import com.tianji.promotion.domain.po.UserCoupon;
import com.tianji.promotion.domain.query.CouponQuery;
import com.tianji.promotion.domain.vo.CouponDetailVO;
import com.tianji.promotion.domain.vo.CouponPageVO;
import com.tianji.promotion.domain.vo.CouponScopeVO;
import com.tianji.promotion.domain.vo.CouponVO;
import com.tianji.promotion.enums.CouponStatus;
import com.tianji.promotion.enums.ObtainType;
import com.tianji.promotion.enums.UserCouponStatus;
import com.tianji.promotion.mapper.CouponMapper;
import com.tianji.promotion.service.ICouponScopeService;
import com.tianji.promotion.service.ICouponService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.promotion.service.IExchangeCodeService;
import com.tianji.promotion.service.IUserCouponService;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.C;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.tianji.promotion.enums.CouponStatus.UN_ISSUE;

/**
 * <p>
 * 优惠券的规则信息 服务实现类
 * </p>
 *
 * @author leiyuhang
 * @since 2023-08-02
 */
@Service
@RequiredArgsConstructor
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {
    private final ICouponScopeService couponScopeService;
    private final IExchangeCodeService codeService;
    private final CategoryClient categoryClient;
    private final IUserCouponService userCouponService;

    @Override
    @Transactional
    public void saveCoupon(CouponFormDTO dto) {
        //1.保存优惠卷
        Coupon coupon= BeanUtils.copyBean(dto,Coupon.class);
        save(coupon);

        if (!dto.getSpecific()){
            return;
        }
        //2.保存限定范围
        Long id = coupon.getId();
        List<Long> scopes = dto.getScopes();
        if (CollUtils.isEmpty(scopes)) {
            throw new BadRequestException("限定范围为空");
        }
        List<CouponScope> collect = scopes.stream().map(bizId -> new CouponScope().setBizId(bizId).setCouponId(id)).collect(Collectors.toList());
        couponScopeService.saveBatch(collect);
    }

    @Override
    public PageDTO<CouponPageVO> queryCouponByPage(CouponQuery query) {
        Integer status = query.getStatus();
        String name = query.getName();
        Integer type = query.getType();
        //1.分页查询
        Page<Coupon> page = lambdaQuery().eq(status != null, Coupon::getStatus, query.getStatus())
                .eq(name != null, Coupon::getName, query.getName())
                .eq(type != null, Coupon::getType, query.getType())
                .page(query.toMpPageDefaultSortByCreateTimeDesc());
        List<Coupon> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        //2.封装数据
        List<CouponPageVO> list= BeanUtils.copyList(records, CouponPageVO.class);
        return PageDTO.of(page,list);
    }

    @Override
    public void beginIssue(CouponIssueFormDTO dto) {
        //1.查询优惠卷
        Coupon coupon = getById(dto.getId());
        if (coupon == null){
            throw new BadRequestException("优惠卷状态错误！");
        }
        //2.判断优惠卷
        if (coupon.getStatus()!= CouponStatus.DRAFT&&coupon.getStatus()!=CouponStatus.PAUSE){
            throw new BizIllegalException("优惠卷状态错误");
        }
        //3.判断是否立即发放
        LocalDateTime issueBeginTime = dto.getIssueBeginTime();
        boolean b =issueBeginTime==null||issueBeginTime.isAfter(LocalDateTime.now());
        //4.更新优惠卷
        Coupon c = BeanUtils.copyBean(dto,Coupon.class);
        if (b){
            c.setStatus(CouponStatus.ISSUING);
            c.setIssueBeginTime(LocalDateTime.now());
        }else {
            c.setStatus(UN_ISSUE);
        }
        updateById(c);
        // 5.判断是否需要生成兑换码
        if(coupon.getObtainWay() == ObtainType.ISSUE && coupon.getStatus() == CouponStatus.DRAFT){
            coupon.setIssueEndTime(c.getIssueEndTime());
            codeService.asyncGenerateCode(coupon);
        }
    }

    @Override
    public void deleteById(Long id) {
        Coupon coupon = getById(id);
        if (coupon==null){
            throw  new BizIllegalException("未查到优惠卷数据");
        }
        if (coupon.getStatus()!=CouponStatus.DRAFT){
            throw  new BizIllegalException("非待发放优惠卷不可删除");
        }
        deleteById(id);
        couponScopeService.removeById(id);
    }

    @Override
    public void updateCoupon(Long id) {
        Coupon coupon = getById(id);
        if (coupon.getStatus()!=CouponStatus.DRAFT){
            throw  new BizIllegalException("非待发放优惠卷不可修改");
        }
    }

    @Override
    public CouponDetailVO getCouponDetailVOById(Long id) {
        Coupon coupon = getById(id);
        CouponDetailVO vo= BeanUtils.copyBean(coupon,CouponDetailVO.class);
        if (coupon.getSpecific()){
            List<CouponScope> list = couponScopeService.lambdaQuery().eq(CouponScope::getCouponId, id).list();
            List<CouponScopeVO> voList = new ArrayList<>();

            List<CategoryBasicDTO> allOfOneLevel = categoryClient.getAllOfOneLevel();
            Map<Long, String> collect = allOfOneLevel.stream().collect(Collectors.toMap(CategoryBasicDTO::getId, CategoryBasicDTO::getName));

            for (CouponScope couponScope : list) {
                CouponScopeVO v = new CouponScopeVO();
                String s = collect.get(couponScope.getBizId());
                v.setId(couponScope.getBizId());
                v.setName(s);
                voList.add(v);
            }
        }
        
        return vo;

    }

    @Override
    public List<CouponVO> queryIssuingCoupons() {
        // 1.查询发放中的优惠券列表
        List<Coupon> coupons = lambdaQuery()
                .eq(Coupon::getStatus, CouponStatus.ISSUING)
                .eq(Coupon::getObtainWay, ObtainType.PUBLIC)
                .list();
        if (CollUtils.isEmpty(coupons)) {
            return CollUtils.emptyList();
        }
        // 2.统计当前用户已经领取的优惠券的信息
        List<Long> couponIds = coupons.stream().map(Coupon::getId).collect(Collectors.toList());
        // 2.1.查询当前用户已经领取的优惠券的数据
        List<UserCoupon> userCoupons = userCouponService.lambdaQuery()
                .eq(UserCoupon::getUserId, UserContext.getUser())
                .in(UserCoupon::getCouponId, couponIds)
                .list();
        // 2.2.统计当前用户对优惠券的已经领取数量
        Map<Long, Long> issuedMap = userCoupons.stream()
                .collect(Collectors.groupingBy(UserCoupon::getCouponId, Collectors.counting()));
        // 2.3.统计当前用户对优惠券的已经领取并且未使用的数量
        Map<Long, Long> unusedMap = userCoupons.stream()
                .filter(uc -> uc.getStatus() == UserCouponStatus.UNUSED)
                .collect(Collectors.groupingBy(UserCoupon::getCouponId, Collectors.counting()));
        // 3.封装VO结果
        List<CouponVO> list = new ArrayList<>(coupons.size());
        for (Coupon c : coupons) {
            // 3.1.拷贝PO属性到VO
            CouponVO vo = BeanUtils.copyBean(c, CouponVO.class);
            list.add(vo);
            // 3.2.是否可以领取：已经被领取的数量 < 优惠券总数量 && 当前用户已经领取的数量 < 每人限领数量
            vo.setAvailable(
                    c.getIssueNum() < c.getTotalNum()
                            && issuedMap.getOrDefault(c.getId(), 0L) < c.getUserLimit()
            );
            // 3.3.是否可以使用：当前用户已经领取并且未使用的优惠券数量 > 0
            vo.setReceived(unusedMap.getOrDefault(c.getId(),  0L) > 0);
        }
        return list;
    }
}
